package com.damagedboy.base.common;

import com.damagedboy.base.exception.ReturnInfoException;
import com.damagedboy.base.po.AdminUserPO;
import com.damagedboy.base.utils.MD5Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private ICommonSV commonSV;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) throws ReturnInfoException {
        try {
            if (StringUtils.isEmpty(username)) {
                throw new ReturnInfoException("-1", "请输入手机号");
            }
            if (StringUtils.isEmpty(password)) {
                throw new ReturnInfoException("-1", "请输入密码");
            }
            String encode = MD5Tools.MD5(password);
            AdminUserPO adminUserPO = commonSV.getAdminUserByUserNameAndPassword(username, encode);

            if (adminUserPO == null) {
                throw new ReturnInfoException("-1", "用户名或者密码错误");
            }

            request.getSession().setAttribute("adminusersession", adminUserPO);
            return adminUserPO;
        } catch (Exception e) {
            throw new ReturnInfoException("-1", "用户名或者密码错误");
        }
    }

    @RequestMapping("/logout")
    public Object logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "ok";
    }

    @RequestMapping("/nopermission")
    public Object nopermission() throws ReturnInfoException {
        throw new ReturnInfoException("nologin", "请重新登录");
    }
}
